package com.aps.apspda.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.PopupWindow;

import com.aps.apspda.base.App;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jaxhuang
 * @date 2017/9/18
 * @desc
 */

public class AppUtils {

    public static boolean isHasLoadMore(int total, int page) {
        int per = total / Integer.parseInt(StaticMembers.PAGE_SIZE);
        if (total % Integer.parseInt(StaticMembers.PAGE_SIZE) != 0) {
            per += 1;
        }
        if (per == page) {
            return false;
        } else {
            return true;
        }
    }

    public static int dip2px(float dpValue) {
        final float scale = App.appContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int sp2px(float spValue) {
        final float fontScale = App.appContext.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int getStatusHeight(Context context) {
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    public static String dateToStr(Date dateDate, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(dateDate);
    }

    public static String createRandom(boolean numberFlag, int length) {
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijklmnopqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

    //邮箱验证
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }

    public static Date stringToDate(String strTime, String formatType) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static boolean isEn() {
        Locale locale = App.appContext.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("en"))
            return true;
        else
            return false;
    }

    public static String getVerName() {
        String verName = "";
        try {
            verName = App.appContext.getPackageManager().
                    getPackageInfo(App.appContext.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public static void showAsDropDown(final PopupWindow pw, final View anchor, final int xoff, final int yoff) {
        if (Build.VERSION.SDK_INT >= 24) {
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            pw.setHeight(height);
            pw.showAsDropDown(anchor, xoff, yoff);
        } else {
            pw.showAsDropDown(anchor, xoff, yoff);
        }
    }

    public static void setSharePre(String sName, String sKey, String sValue) {
        SharedPreferences s = App.appContext.getSharedPreferences(sName, 0);
        SharedPreferences.Editor editor = s.edit();
        editor.putString(sKey, sValue);
        editor.commit();
    }

    public static String getSharePre(String sName, String sKey) {
        String str;
        SharedPreferences s = App.appContext.getSharedPreferences(sName, 0);
        str = s.getString(sKey, "");
        return str;
    }

    public static String getFormatStr(Object str) {
        if (str == null) {
            return "";
        } else {
            if (str instanceof String) {
                return String.valueOf(str);
            } else {
                DecimalFormat decimalFormat = new DecimalFormat("#");
                return decimalFormat.format(str);
            }
        }
    }

    /**
     * 2.保存错误信息
     *
     * @param e Throwable
     */
    public static void saveErrorMessages(Throwable e, String method) {
        StringBuffer sb = new StringBuffer();
        sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date()));
        sb.append(" ");
        sb.append(StaticMembers.CUR_USER.getUSERNAME().length() > 0 ? StaticMembers.CUR_USER.getUSERNAME() : "未登录");
        sb.append(" ");
        sb.append(StaticMembers.LOG_EQP_ID.length() > 0 ? StaticMembers.LOG_EQP_ID : "无设备");
        sb.append(" ");
        sb.append(method);
        sb.append("\n");
        sb.append(Log.getStackTraceString(e));
        sb.append("\n");

        String fileName = "crash" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()) + ".log";
        // 有无SD卡
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(StaticMembers.logRootPath);
            if (!dir.exists()) dir.mkdirs();
            RandomAccessFile raf = null;
            File logFile = new File(StaticMembers.logRootPath + fileName);
            try {
                raf = new RandomAccessFile(logFile, "rw");
                raf.seek(logFile.length());
                raf.write(sb.toString().getBytes());
            } catch (Exception e1) {
                e1.printStackTrace();
            } finally {
                if (raf != null) {
                    try {
                        raf.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    public static void saveErrorMessages(String e, String method) {
        StringBuffer sb = new StringBuffer();
        sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date()));
        sb.append(" ");
        sb.append(StaticMembers.CUR_USER.getUSERNAME().length() > 0 ? StaticMembers.CUR_USER.getUSERNAME() : "未登录");
        sb.append(" ");
        sb.append(StaticMembers.LOG_EQP_ID.length() > 0 ? StaticMembers.LOG_EQP_ID : "无设备");
        sb.append(" ");
        sb.append(method);
        sb.append("\n");
        sb.append(e);
        sb.append("\n");

        String fileName = "crash" + new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()) + ".log";
        // 有无SD卡
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(StaticMembers.logRootPath);
            if (!dir.exists()) dir.mkdirs();
            RandomAccessFile raf = null;
            File logFile = new File(StaticMembers.logRootPath + fileName);
            try {
                raf = new RandomAccessFile(logFile, "rw");
                raf.seek(logFile.length());
                raf.write(sb.toString().getBytes());
            } catch (Exception e1) {
                e1.printStackTrace();
            } finally {
                if (raf != null) {
                    try {
                        raf.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    public static void deleteLog() {
        File file = new File(StaticMembers.logRootPath);
        if (!file.exists()) {//判断路径是否存在
            return;
        }
        File[] fileArray = file.listFiles();
        if (fileArray == null) {//判断权限
            return;
        }
        String day1 = getOldDate(1);
        String day2 = getOldDate(2);
        String day3 = getOldDate(3);
        String day = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date());


        for (int i = 0; i < fileArray.length; i++) {
            File logFile = fileArray[i];
            boolean isOutTime = true;
            if (logFile.getName().equals("crash" + day + ".log") ||
                    logFile.getName().equals("crash" + day1 + ".log") ||
                    logFile.getName().equals("crash" + day2 + ".log") ||
                    logFile.getName().equals("crash" + day3 + ".log")) {
                isOutTime = false;
            }
            if (isOutTime) {
                logFile.delete();
            }
        }
    }

    public static String getOldDate(int distanceDay) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(Calendar.DATE, date.get(Calendar.DATE) - distanceDay);
        Date endDate = null;
        try {
            endDate = dft.parse(dft.format(date.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dft.format(endDate);
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
